from django.shortcuts import render
from .ml import DeepLearn
from django.http import JsonResponse
import os


# Create your views here.
def index(request):
    """mnist首页请求"""
    return render(request, 'mnist/index.html')


def upload(request):
    """
    file_path_url，file_path
    :param request:
    :return:
    """
    if request.method == "POST":
        ret = {"status": False, "data": False, "error": None}
        # f = None
        try:
            img = request.FILES.get("img")
            FILE_PATH = os.path.abspath(os.path.dirname(__file__)) + os.sep + "static" + os.sep + img.name
            FILE_PATH_URL = "/static/" + img.name  # 前端展示图片
            # 上传的图片写入本地
            f = open(FILE_PATH, "wb")
            for chunk in img.chunks(chunk_size=1024 * 1024):
                f.write(chunk)
            ret["status"] = True
            # ret["data"] = FILE_PATH_URL
        except Exception as e:
            print(e)
            ret["error"] = e
            return JsonResponse({"file_path": "", "file_path_url": "", "status": ret["status"], "error": ret["error"]})
        finally:
            # f.close()
            pass

        return JsonResponse(
            {"file_path": FILE_PATH, "file_path_url": FILE_PATH_URL, "status": ret["status"], "error": ret["error"]})


def pred(request):
    """数字识别请求"""
    file_path = request.POST.get("file_path", None)
    logic_select = request.POST.get("logic_select", None)
    res_pred = ""
    dl = DeepLearn(file_path)
    if logic_select == "DNN_Keras":
        pred, score = dl.dnn_keras()
    return JsonResponse({"msg": f"预测的结果:{pred}", "acc": f"正确率:{score}"})
